 function f     = jacobLogit(theta,delta,Data)

% jacobLogit - This function is calculate the derivative of the mean value
% delta wrt the parameter using the implicit function theorem (see Nevo
% http://faculty.wcas.northwestern.edu/~ane686/supplements/Ras_guide_appendix.pdf
% 
% 
% jacobLogit(theta,delta,Data)
%
% Inputs:
%    input1 - Non linear parameters
%    input2 - Data
%
% Outputs:
%    Derivative of Delta wrt theta 
%
% Subfunctions: LogitShareCalculation; multinv; multiprod
%

% Author: Laura Grigolon
% August 2012;
 
% Unpack
prods           = Data.prods;
multixvuL       = Data.multixvuL;
qweightrprods   = Data.qweightrprods;

% Market Shares
[~, sij]        = LogitShareCalculation(theta,delta,Data);

% Jacobian
% remember that sij is prod x 1 x mkt x nodes

% derivative of shares wrt to delta
part1           = bsxfun(@times,sij,eye(prods));          % diagonal in multiple dimensions
sijtransp       = permute(sij,[2 1 3 4]);
part2           = multiprod(sij,sijtransp);
derShareDeltij  = part1 - part2;
derShareDelta   = sum((bsxfun(@times,derShareDeltij,qweightrprods)),4);

% derivative of shares with respect to random coefficient
part1           = bsxfun(@times,multixvuL,sij);
part2           = bsxfun(@times,sum(part1),sij);
derShareRC1     = part1-part2;
derShareTheta   = sum((bsxfun(@times,derShareRC1,qweightrprods)),4);


derDeltaTheta   = multiprod((-multinv(derShareDelta)),derShareTheta);
derDeltaTheta   = reshape(derDeltaTheta,[Data.nobs 1]); % 2D market shares
f = derDeltaTheta;

end